package com.zhuhjay.framework.security.service;

import com.zhuhjay.common.base.exception.BasicBusinessException;
import com.zhuhjay.common.security.LoginUserDetail;
import com.zhuhjay.framework.security.SpecificUserInfo;
import com.zhuhjay.service.system.model.entity.SystemUser;
import com.zhuhjay.service.system.service.SystemUserService;
import org.springframework.security.core.userdetails.UserDetails;
import org.springframework.security.core.userdetails.UserDetailsService;
import org.springframework.security.core.userdetails.UsernameNotFoundException;
import org.springframework.stereotype.Service;

import javax.annotation.Resource;

/**
 * @author ZhuHJay
 * @date 2023/2/25 11:48
 */
@Service
public class UserDetailsServiceImpl implements UserDetailsService {

    @Resource
    private SystemUserService userService;

    /** 登录时获取数据库中用户的信息 **/
    @Override
    public UserDetails loadUserByUsername(String username) throws UsernameNotFoundException {
        // 查询用户信息
        SystemUser user = userService.lambdaQuery()
                .eq(SystemUser::getUsername, username).one();
        // 检查有效性
        if (user == null) {
            // 如果使用 UsernameNotFoundException，SpringSecurity 将会隐藏该错误信息，打印 "用户名或密码错误"
            throw new BasicBusinessException("登录用户: {" + username + "} 不存在");
        }
        if (user.getStatus() == 0) {
            throw new BasicBusinessException("登录用户: {" + username + "} 已被停用");
        }
        // 封装用户信息接受下一步的密码校验
        return new LoginUserDetail(SpecificUserInfo.of(user));
    }

}
